﻿using log4net.Appender;
using NetFrame.JobService;
using NetFrame.Model;
using NetFrame.Persistance;
using NetFrame.UI;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace NetFrame
{
    public partial class MainForm : Form, IAppender
    {

        List<Job> _jobs = new List<Job>();

        public MainForm()
        {
            InitializeComponent();
            jobsDataView.DataSource = InitiaJobs();
         
        }

       

        private void jobEditToolStripMenuItem_Click(object sender, EventArgs e)
        {
            JobManagement jobs = new JobManagement();
            jobs.Show();
        }

        private ArrayList InitiaJobs()
        {
            
            var scheduler = SchedulerManager.Instance.Scheduler;
            var groups = scheduler.JobGroupNames;
            BasePersistance<Job>.DoAction((t) =>
            {
                _jobs = t.Adapter.Select().OrderBy(k => k.Id).ToList();
            });
            var list=new ArrayList();
            foreach (var job in _jobs)
            {
                var detail = scheduler.GetTrigger(job.Triger, "DefaultJobGroup");
                if (detail != null)
                {
                    list.Add(new
                    {
                        JobName = job.JobName,
                        Triger = job.Triger,
                        RowStatus = job.RowStatus == 1 ? "有效" : "无效",
                        RegCron = job.RegCron,
                        Remark = job.Remark,
                        TriggerState = scheduler.GetTriggerState(job.Triger, "DefaultJobGroup").ToString(),
                        PreviousFire = detail.GetPreviousFireTimeUtc().GetValueOrDefault().ToLocalTime().ToString(),
                        NextFire = detail.GetNextFireTimeUtc().GetValueOrDefault().ToLocalTime().ToString(),
                        FireAgain = detail.GetMayFireAgain() ? "是" : "否"
                    });
                }
                else
                {
                    list.Add(new
                    {
                        JobName = job.JobName,
                        Triger = job.Triger,
                        RowStatus = job.RowStatus == 1 ? "有效" : "无效",
                        RegCron = job.RegCron,
                        Remark = job.Remark,
                        TriggerState = "已停止",
                        PreviousFire = "已停止",
                        NextFire = "已停止",
                        FireAgain = "否"
                    });
                }
            }
            return list;
        }

        private void jobsTimer_Tick(object sender, EventArgs e)
        {
            jobsDataView.DataSource = InitiaJobs();
            logRichText.Text = string.Join("\r\n", logList.ToArray());
            logList.Clear();
        }

        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            SchedulerManager.Instance.ShutDown();
        }

        List<string> logList = new List<string>();

        public void DoAppend(log4net.Core.LoggingEvent loggingEvent)
        {
            logList.Add(String.Format("log4net - {0}: {1}  {2}", loggingEvent.Level.Name, loggingEvent.MessageObject.ToString(), loggingEvent.TimeStamp));
        }

        private void jobsDataView_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            foreach (DataGridViewRow row in jobsDataView.Rows)
            {
                row.Selected = false;
            }
            if (e.RowIndex < 0) return;
            jobsDataView.Rows[e.RowIndex].Selected = true;
        }

        private void allJobToolStripButton_Click(object sender, EventArgs e)
        {
            if (allJobToolStripButton.Text == "任务暂停")
            {
                allJobToolStripButton.Text = "任务启动";
                allJobToolStripButton.Select();
                JobService.JobService.StopJob(_jobs[jobsDataView.SelectedRows[0].Index].JobName);
                
            }
            else
            {
                allJobToolStripButton.Text = "任务暂停";
                JobService.JobService.ResumeJob(_jobs[jobsDataView.SelectedRows[0].Index].JobName);
            }
        }
    }
}
